import React, { useState, useEffect, useCallback, useMemo } from 'react';
import Search from 'antd/lib/input/Search';
import { Space, Button, Table, message, Modal } from 'antd';

import { ColumnsType } from 'antd/lib/table';
import { deleteFlowDebugRecord, getFlowDebugRecordList } from 'admin/servers/servers'; // http接口请求文件
import { FlowDebugRecordInfo } from 'admin/schema/FlowDebugRecord';
import FlowDebugRecordDetail from './components/FlowDebugRecordDetail';
import moment from 'moment';
import { LeftOutlined } from '@ant-design/icons';
import { useHistory, useLocation } from 'react-router-dom';

import qs from 'query-string';
import { deleteRowChangePageNum } from 'utils/tools';
/**
 * 流程调试记录列表
 */
const FlowDebugRecord: React.FC = () => {
  const history = useHistory();
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);

  const versionId = Number(query.versionId);
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');
  // table列表数据
  const [flowDebugRecord, setFlowDebugRecord] = useState<FlowDebugRecordInfo[]>([]);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailId, setDetailId] = useState<string>('');

  /**
   * 查询table数据
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getFlowDebugRecordList({
        pageNo: current,
        pageSize: pageSize,
        calledNumber: searchText,
        versionId,
      });
      const { data, count } = res;
      setFlowDebugRecord(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, searchText, versionId]);

  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 搜索流程调试记录
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    text = text.trim();
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };

  /**
   * 查看详情-流程调试记录
   */
  const handleDetail = async (flowDedugRecordId: string) => {
    setDetailVisible(true);
    setDetailId(flowDedugRecordId);
  };
  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }
  /**
   * 删除流程调试记录
   */
  const handleDelete = (flowDedugRecordId: string) => {
    Modal.confirm({
      title: '删除记录提示',
      content: '删除后无法恢复! 确认删除吗?',
      onOk: () => {
        deleteFlowDebugRecord(flowDedugRecordId)
          .then(res => {
            message.success('删除成功');
            deleteFresh(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };

  /**
   * Table列描述数据对象
   */

  const columns: ColumnsType<FlowDebugRecordInfo> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 100,
    },
    {
      title: '被叫号码',
      dataIndex: 'calledNumber',
    },
    {
      title: '主叫号码',
      dataIndex: 'callerNumber',
    },
    {
      title: '语音识别厂商',
      dataIndex: 'mrcpIdentifierName',
    },
    {
      title: 'TTS',
      dataIndex: 'ttsProviderIdentifierName',
    },
    {
      title: '录音',
      dataIndex: 'recordTemplateName',
    },
    {
      title: '调试时间',
      dataIndex: 'debugTime',
      render: (text, record, index) => {
        return moment(Number(text)).format('YYYY-MM-DD HH:mm');
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record, index) => (
        <Space size="small">
          <Button type="link" onClick={() => handleDetail(record.flowDedugRecordId)}>
            详情
          </Button>
          <Button type="link" onClick={() => handleDelete(record.flowDedugRecordId)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div className="nav">
        <Button
          type="link"
          onClick={() => {
            history.goBack();
          }}
        >
          <LeftOutlined />
          返回
        </Button>
        <div className="title">流程调试记录</div>
      </div>
      <div className="mgr-header" style={{ marginTop: '20px' }}>
        <div className="mgr-header-left">
          <Search
            placeholder="请输入被叫号码"
            enterButton="搜索"
            style={{ width: 300 }}
            onSearch={value => handleSearch(value)}
          />
        </div>
      </div>
      <div className="mgr-table">
        <Table
          loading={tableLoading}
          columns={columns}
          dataSource={flowDebugRecord}
          rowKey="flowDedugRecordId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
      {detailVisible && (
        <FlowDebugRecordDetail
          visible={detailVisible}
          flowDedugRecordId={detailId}
          onClose={() => {
            setDetailVisible(false);
          }}
        ></FlowDebugRecordDetail>
      )}
    </>
  );
};

export default FlowDebugRecord;
